package site.enjoyrun.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import site.enjoyrun.model.User;
import site.enjoyrun.service.UserService;
import site.enjoyrun.utils.Result;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping("/")
    public Result getUsers() {
        Result res = new Result();

        List<User> users = userService.getAllUser();

        if(users == null) {
            res.setMsg("数据获取失败！");
            res.setCode(10500);
        } else {
            res.setMsg("数据获取成功！");
            res.setCode(10200);
        }
        res.setData(users);
        return res;
    }

    @PostMapping("/insert")
    public Result insert(User user) {
        Result res = new Result();
        if(userService.insertUser(user)) {
            res.setCode(10200);
            res.setMsg("数据插入成功！");
            res.setData(new Boolean(true));
        } else {
            res.setCode(10500);
            res.setMsg("数据异常或者服务器出错！");
            res.setData(new Boolean(false));
        }
        return res;
    }

    @PutMapping("/update")
    public Result updateUser(User user) {
        Result res = new Result();

        if(userService.updateUser(user)) {
            res.setCode(10200);
            res.setMsg("数据修改成功！");
            res.setData(new Boolean(true));
        } else {
            res.setCode(10500);
            res.setMsg("数据异常或者服务器出错！");
            res.setData(new Boolean(false));
        }

        return res;
    }


    @DeleteMapping("/delete/{uId}")
    public Result deleteUser(@PathVariable("uId") String uId) {
        Result res = new Result();
        if(uId == null) {
            res.setCode(10501);
            return res;
        }

        System.out.println(uId);

        if(uId != null && userService.deleteUser(uId)) {
            res.setCode(10200);
            res.setMsg("数据删除成功！");
            res.setData(new Boolean(true));
        } else {
            res.setCode(10500);
            res.setMsg("数据异常或者服务器出错！");
            res.setData(new Boolean(false));
        }
        return res;
    }
}
